﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using NangLuongTieuDiemBUS;
using NangLuongTieuDiemDTO.DTO;

namespace NangLuongTieuDiemGUI.NangLuongTieuDiemUserControl
{
    public partial class ucTinhCongSuatThietBiDien : UserControl
    {
        /// <summary>
        /// Mr.chau
        /// 3/6/2013
        /// </summary>
        public DelegateShowItem showItem = null;
        public DelegateShowItem showLapHoaDonUC = null;

        #region "[khai báo biến local]"
           int stt = 1;
            int flag = 0;
            DataTable dt;
            public static double tongcongsuat;
        #endregion
       

        #region "[khởi tạo mặc định]"
        public ucTinhCongSuatThietBiDien()
        {
            InitializeComponent();
        }
        #endregion
       

        #region  "[Load]"
        /// <summary>
        /// Load
        /// </summary>
        private void groupControl1_Paint(object sender, PaintEventArgs e)
        {
            try
            {
                // add thong tin cot vao datatable
                dt = new DataTable();
                dt.Columns.Add(new DataColumn("Stt"));
                dt.Columns.Add(new DataColumn("TenTB"));
                dt.Columns.Add(new DataColumn("CongSuat"));
                dt.Columns.Add(new DataColumn("CongSuatHaoHut"));
                dt.Columns.Add(new DataColumn("HeSoDeBa"));
                dt.Columns.Add(new DataColumn("SoLuong"));
                dt.Columns.Add(new DataColumn("ThoiGianSuDung"));
                dt.Columns.Add(new DataColumn("TongCongSuat"));

                // gan datatable vao grid control
                dgvDanhSachThietBiDuocChon.DataSource = dt;


                // danh sach thiet bi dien lay tu database 
                List<ThietBiDienDTO> dsthietbidien = new List<ThietBiDienDTO>();
                dsthietbidien = NangLuongTieuDiem_Management.ThietBiDien_GetAll();


                repositoryItemGridLookUpEdit_ThietBiDien.DataSource = dsthietbidien;
                repositoryItemGridLookUpEdit_ThietBiDien.ValueMember = "ID";
                repositoryItemGridLookUpEdit_ThietBiDien.DisplayMember = "TenThietBiDien";

                // add data vao gridlookupedit 
                TenTB.ColumnEdit = repositoryItemGridLookUpEdit_ThietBiDien;
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("groupControl1_Paint", ex);
                throw;
            }

        }
        #endregion


        #region "[sự kiện click 1 dòng trên grid thiết bị điện]"
        private void repositoryItemGridLookUpEdit_ThietBiDien_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                // Lay thong tin thiet bi dien duoc chon tren grid lookupedit

                DevExpress.XtraEditors.GridLookUpEdit grid_lookupedit = sender as DevExpress.XtraEditors.GridLookUpEdit;
                string MaTB = grid_lookupedit.Properties.View.GetFocusedRowCellValue("ID").ToString();
                string CongSuat = grid_lookupedit.Properties.View.GetFocusedRowCellValue("CongSuat").ToString();
                string CongSuatHaoHut = grid_lookupedit.Properties.View.GetFocusedRowCellValue("CongSuatHaoHut").ToString();
                string HeSoDeBa = grid_lookupedit.Properties.View.GetFocusedRowCellValue("HeSoDeBa").ToString();

                // Set gia tri vao grid control

                gridview_Thietbidien.SetFocusedRowCellValue("MaTB", MaTB);
                gridview_Thietbidien.SetFocusedRowCellValue("CongSuat", CongSuat);
                gridview_Thietbidien.SetFocusedRowCellValue("CongSuatHaoHut", CongSuatHaoHut);
                gridview_Thietbidien.SetFocusedRowCellValue("HeSoDeBa", HeSoDeBa);
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("repositoryItemGridLookUpEdit_ThietBiDien_EditValueChanged", ex);
                throw;
            }

        }    
        #endregion


        #region "[sự kiện khi giá trị của cell trên grid thay đổi]"
        private void gridview_Thietbidien_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            //try
            //{
                
            //    // kiem tra co thuc hien su kien khong
            //    if (flag == 1)
            //    {
            //        flag = 0;
            //        return;
            //    }


            //    // lay thong tin du lieu duoc nhap tren luoi
            //    string sl = gridview_Thietbidien.GetFocusedRowCellValue("SoLuong").ToString();
            //    string tgsd = gridview_Thietbidien.GetFocusedRowCellValue("ThoiGianSuDung").ToString();
            //    string tenthietbi = gridview_Thietbidien.GetFocusedRowCellValue("TenTB").ToString();

            //    // kiem tra du lieu nhap vao la so
            //    double temp;
            //    if (double.TryParse(sl, out temp) == false && sl != "")
            //    {
            //        ClassUtils.Utils.MassageBoxErrorOtInformation("Nhập lại!  Số lượng phải là số ", "Thông báo", true);
            //        return;

            //    }

            //    if (double.TryParse(tgsd, out temp) == false && tgsd != "")
            //    {
            //        ClassUtils.Utils.MassageBoxErrorOtInformation("Nhập lại!  Thời gian sử dụng phải là số ", "Thông báo", true);
            //        return;
            //    }


            //    // tinh tong cong suat cua thiet bi
            //    if (sl != "" && tgsd != "" && tenthietbi != "")   // cot so luong va cot thoi gian su dung duoc nhap
            //    {

            //        double TongCongSuat;
            //        double CongSuat = Convert.ToDouble(gridview_Thietbidien.GetFocusedRowCellValue("CongSuat").ToString());
            //        double CongSuatHaoHut = Convert.ToDouble(gridview_Thietbidien.GetFocusedRowCellValue("CongSuatHaoHut").ToString());
            //        double HeSoDeBa = Convert.ToDouble(gridview_Thietbidien.GetFocusedRowCellValue("HeSoDeBa").ToString());
            //        double SoLuong = Convert.ToDouble(sl);
            //        double ThoiGianSuDung = Convert.ToDouble(tgsd);
            //        TongCongSuat = (CongSuat + CongSuatHaoHut) * HeSoDeBa * ThoiGianSuDung * SoLuong;
                                
                   
            //        flag = 1;

            //        gridview_Thietbidien.SetFocusedRowCellValue("TongCongSuat", Convert.ToString(TongCongSuat) + " (W)");


            //    }
            //}
            //catch (Exception ex)
            //{
            //    InSert_LoiHeThong("gridview_Thietbidien_CellValueChanged", ex);
            //    throw;
            //}

        }

        #endregion


        #region "[set thông tin stt của 1 dòng mới được thêm trên grid tổng công suất]"
        private void gridview_Thietbidien_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            try
            {
                // set gia tri cho Stt tren grid control
                gridview_Thietbidien.SetFocusedRowCellValue("Stt", stt.ToString());

                stt++;
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("gridview_Thietbidien_InitNewRow", ex);
                throw;
            }

        }
        #endregion


        #region "[Tính tổng công suất tất cả thiết bị]"
            
            private void gridview_Thietbidien_BeforeLeaveRow(object sender, DevExpress.XtraGrid.Views.Base.RowAllowEventArgs e)
            {
                try
                {
                    DataRow row = dt.NewRow();
                    double sum_tongcongsuat = 0;
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        row = dt.Rows[i];

                        if (row["TongCongSuat"].ToString() != "")
                        {
                            ;
                            string tcs = row["TongCongSuat"].ToString();
                            string[] mang = tcs.Split(' ');

                            sum_tongcongsuat = sum_tongcongsuat + Convert.ToDouble(mang[0]);

                        }

                    }
                    tongcongsuat = sum_tongcongsuat;
                    txt_tongcongsuat.Text = sum_tongcongsuat.ToString() + " (W)";
                    Program.m_CongSuatThietBi = sum_tongcongsuat;
                }
                catch (Exception ex)
                {
                    InSert_LoiHeThong("gridview_Thietbidien_BeforeLeaveRow", ex);
                    throw;
                }
                
            }
        #endregion

        #region "[tự chọn sản phẩm dựa theo công suất]"
        /// <summary>
        /// Mr.chau
        /// 3/6/2013
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnchonpintudong_Click(object sender, EventArgs e)
        {
            try {
                if (showLapHoaDonUC != null)
                    showLapHoaDonUC(false);
            }
            catch (Exception ex) 
            {
                InSert_LoiHeThong("btnchonpintudong_Click", ex);
            }
        }
        #endregion

        #region "[Thoát]"
        /// <summary>
        /// Mr.chau
        /// 6/3/2013
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnThoat_Click(object sender, EventArgs e)
        {
            try {
                if (showItem != null)
                    showItem(false);
            }
            catch(Exception ex)
            {
                InSert_LoiHeThong("btnThoat_Click", ex);
            }
        }
        #endregion

        private void btn_open_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog open = new OpenFileDialog();
                open.Filter = "File Excell|*.xls";
                DialogResult result = open.ShowDialog();
                if (result == DialogResult.OK)
                {
                    //lấy đường dẫn.
                    txtDuongDan.Text = open.FileName;
                }

                string strPath = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + txtDuongDan.Text + "';Extended Properties=Excel 8.0;";
                string strsql = "select * from [Sheet" + "1" + "$]";
                System.Data.OleDb.OleDbConnection MyConnection;
                DataSet DtSet;
                System.Data.OleDb.OleDbDataAdapter MyCommand;
                MyConnection = new System.Data.OleDb.OleDbConnection(strPath);
                MyCommand = new System.Data.OleDb.OleDbDataAdapter(strsql, MyConnection);
                //MyCommand.TableMappings.Add("Table", "TestTable");
                DtSet = new DataSet();
                MyCommand.Fill(DtSet);
                DataTable  dt_excel = DtSet.Tables[0];
                MyConnection.Close();

                TenTB.ColumnEdit = null;
                dt.Clear();
                for (int i = 0; i < dt_excel.Rows.Count; i++)
                {
                    DataRow dr = dt.NewRow();
                 
                    dr["TenTB"] = dt_excel.Rows[i][1];
                    dr["CongSuat"] = dt_excel.Rows[i][2];
                    dr["CongSuatHaoHut"] = dt_excel.Rows[i][3];
                    dr["HeSoDeBa"] = dt_excel.Rows[i][4];
                    dr["SoLuong"] = dt_excel.Rows[i][5];
                    dr["ThoiGianSuDung"] = dt_excel.Rows[i][6];
                    dt.Rows.Add(dr);
                }
                              
                dgvDanhSachThietBiDuocChon.DataSource = dt;


            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("txtDuongDan_DoubleClick", ex);
            }
        }


        private void Tinhtongcongsuat(DataTable dt)
        {
            try
            {
                double sum = 0;
                for (int i = 0; i < dt.Rows.Count; i++)
                {


                    string sl = dt.Rows[i]["SoLuong"].ToString();
                    string tgsd = dt.Rows[i]["ThoiGianSuDung"].ToString();
                    string congsuat = dt.Rows[i]["CongSuat"].ToString();
                    string congsuathaohut = dt.Rows[i]["CongSuatHaoHut"].ToString();
                    string hesodeba = dt.Rows[i]["HeSoDeBa"].ToString();

                    if (sl != "" && tgsd != "" && congsuat != "" && congsuathaohut != "" && hesodeba != "")
                    {
                        double TongCongSuat;
                        double CongSuat = Convert.ToDouble(congsuat);
                        double CongSuatHaoHut = Convert.ToDouble(congsuathaohut);
                        double HeSoDeBa = Convert.ToDouble(hesodeba);
                        double SoLuong = Convert.ToDouble(sl);
                        double ThoiGianSuDung = Convert.ToDouble(tgsd);
                        TongCongSuat = (CongSuat + CongSuatHaoHut) * HeSoDeBa * ThoiGianSuDung * SoLuong;

                        sum += TongCongSuat;
                    }

                }

                txt_tongcongsuat.Text = sum + " (W)";
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("Tinhtongcongsuat", ex);               
            }
           
        }

        private void btn_tinhcongsuat_Click(object sender, EventArgs e)
        {
            Tinhtongcongsuat(dt);
        }

        #region "[Hàm insert lỗi hệ thống]"
        public void InSert_LoiHeThong(string TenHam, Exception ex)
        {
            LoiHeThongDTO lhtDto = new LoiHeThongDTO();
            lhtDto.TenLoi = ex.Message.ToString();
            lhtDto.NgayTao = DateTime.Now;
            lhtDto.TenHamBiLoi = "ucTinhCongSuatThietBiDien_" + TenHam;
            lhtDto.SuaLoi = false;
            lhtDto.GhiChu = "";
            NangLuongTieuDiem_Management.LoiHeThong_Insert(lhtDto);
            MessageBox.Show(lhtDto.TenLoi);
        }
        #endregion
    }
}
